'use strict';

var page4 = angular.module('page4', ['ui.bootstrap', 'ngRoute', 'ui.multiselect'],
    function ($httpProvider) {
        // 头部配置
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        $httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript, */*; q=0.01';
        $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
    }
);

//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
//page4.value('glparam',{"isLogin":false});

page4.config(['$routeProvider', '$locationProvider', '$sceProvider', function ($routeProvider, $locationProvider, $sceProvider) {
    $routeProvider
        .when('/', {
            //controller: 'DoLoginCtrl',
            templateUrl: 'figure/about.html',
            publicAccess: true
        })
        .when('/login', {
            controller: 'DoLoginCtrl',
            templateUrl: 'figure/html/security/login.html',
            publicAccess: true
        })
        .when('/index', {
            controller: 'NavbarCtrl',
            templateUrl: 'figure/about.html',
            publicAccess: true
        })
        .when('/role', {
            controller: 'customersCtrl',
            templateUrl: 'figure/html/security/roleList.html',
            publicAccess: true
        })
        .when('/addAccount', {
            controller: 'addAccountCtrl',
            templateUrl: 'figure/html/security/addAccount.html',
            publicAccess: true
        })
        .when('/table-example', {
            controller: 'TableExampleCtrl',
            templateUrl: 'figure/html/table-example.html'
        })
        .when('/item', {
            controller: 'itemCtrl',
            templateUrl: 'figure/html/item/item.html',
            publicAccess: true
        })
        .when('/banner', {
            controller: 'bannerCtrl',
            templateUrl: 'figure/html/item/banner.html',
            publicAccess: true
        })
        .when('/addBanner', {
            controller: 'addBannerCtrl',
            templateUrl: 'figure/html/item/addBanner.html',
            publicAccess: true
        })
        .otherwise({redirectTo: '/'});
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
}]);

page4.controller('NavbarCtrl', function ($scope,$rootScope,$http,$location) {
    $scope.isLogin = false;

    $scope.submit = function() {
        var pData = {username:$scope.username,password:$scope.password};
        $http({
            url:'figure/services/admin/security/login.json',
            method: 'POST',
            params: pData
        }).success(function(result){
            if(result.status.code=='0'){
                //alert(result.success);
                //$location.path('/about');
                $http.get("figure/services/admin/security/index.json").success(function(json){//../js/vm/nav.json
                    if(json.success || json.success=='true'){
                        $scope.navbar = json;
                        $scope.isLogin = true;
                        $scope.nickName = json.userFormMap.name;
                    }else{
                        alert(json.success);
                    }
                });
            }else{
                $location.path('/');
                alert(result.status.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            $location.path('/');
        })
    };

    $scope.loginOut = function() {
        var url = "figure/services/admin/security/logout.json";
        $http.get(url).success(function (result) {
            $location.path('/');
            $scope.isLogin=false;
            //window.location.href = "../login.html";
            //$scope.doOpenMsg = result.APIResult.status.msg;//console.log();//$.alert({ body: result.APIResult.status.msg, height: 150 });
        });
    };
});

page4.controller('customersCtrl', function($scope, $rootScope, $http,$location) {
    $scope.selects = [
        {name : "是", value : "0"},
        {name : "否", value : "1"}
    ];
    $scope.queryBtn = function() {
        var pData = {name:$scope.name,status:$scope.status};
        $http({
            url:'figure/services/admin/security/roleList.json',
            method: 'POST',
            params: pData
        }).success(function(result){
            if(result.success){
                $scope.items = result.data.resultList;
            }else{
                alert(result.msg);
            }
        }).error(function(){
            console.log("error");
        })
    };
//        $http.get("/try/angularjs/data/Customers_JSON.php")
//                .success(function (response) {$scope.items = response.records;});
});

page4.controller('addAccountCtrl', function($scope, $rootScope, $http,$location) {
    $scope.submit = function() {
        var pData = {userName:$scope.userName,accountName:$scope.accountName,password:$scope.password,description:$scope.description};
        $http({
            url:'figure/services/admin/security/addAccount.json',
            method: 'POST',
            params: pData
        }).success(function(result){
            if(result.success){
                //alert(result.success);
                $location.path('/about');
            }else{
                $location.path('/');
                alert(result.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            $location.path('/');
        })
    };
});

page4.controller('itemCtrl', function($scope, $rootScope, $http,$location) {
    $scope.keyword='手办';
    var creditSelects = [
        {name : "一心", value : "1heart"},
        {name : "两心", value : "2heart"},
        {name : "三心", value : "3heart"},
        {name : "四心", value : "4heart"},
        {name : "五心", value : "5heart"},
        {name : "一钻", value : "1diamond"},
        {name : "两钻", value : "2diamond"},
        {name : "三钻", value : "3diamond"},
        {name : "四钻", value : "4diamond"},
        {name : "五钻", value : "5diamond"},
        {name : "一冠", value : "1crown"},
        {name : "两冠", value : "2crown"},
        {name : "三冠", value : "3crown"},
        {name : "四冠", value : "4crown"},
        {name : "五冠", value : "5crown"},
        {name : "一黄冠", value : "1goldencrown"},
        {name : "二黄冠", value : "2goldencrown"},
        {name : "三黄冠", value : "3goldencrown"},
        {name : "四黄冠", value : "4goldencrown"},
        {name : "五黄冠", value : "5goldencrown"}
    ];
    $scope.startCreditSelects = creditSelects;
    $scope.endCreditSelects = creditSelects;

    $scope.startCredit = '1heart';
    $scope.endCredit = '5goldencrown';

    $scope.sortSelects = [
        {name : "价格从高到低", value : "price_desc"},
        {name : "价格从低到高", value : "price_asc"},
        {name : "信用等级从高到低", value : "credit_desc"},
        {name : "佣金比率从高到低", value : "commissionRate_desc"},
        {name : "佣金比率从低到高", value : "commissionRate_asc"},
        {name : "成交量成高到低", value : "commissionNum_desc"},
        {name : "成交量从低到高", value : "commissionNum_asc"},
        {name : "总支出佣金从高到低", value : "commissionVolume_desc"},
        {name : "总支出佣金从低到高", value : "commissionVolume_asc"},
        {name : "商品下架时间从高到低", value : "delistTime_desc"},
        {name : "商品下架时间从低到高", value : "delistTime_asc"}
    ];
    $scope.sort = $scope.sortSelects[0].value;

    $scope.queryBtn = function() {
        var pData = {keyword:$scope.keyword,sort:$scope.sort.value,area:$scope.area,
            startCredit:$scope.startCredit.value, endCredit:$scope.endCredit.value,
            startPrice:$scope.startPrice, endPrice:$scope.endPrice,
            startCommissionRate:$scope.startCommissionRate, endCommissionRate:$scope.endCommissionRate,
            startTotalnum:$scope.startTotalnum, endTotalnum:$scope.endTotalnum,
            startCommissionNum:$scope.startCommissionNum, endCommissionNum:$scope.endCommissionNum,
            cashCoupon:$scope.cashCoupon, guarantee:$scope.guarantee, mallItem:$scope.mallItem,
            onemonthRepair:$scope.onemonthRepair, overseasItem:$scope.overseasItem, realDescribe:$scope.realDescribe, sevendaysReturn:$scope.sevendaysReturn, supportCod:$scope.supportCod,
            vipCard:$scope.vipCard};
        var url = 'figure/services/item/getAtbItems.json';
        $http({
            url:url,
            method: 'POST',
            params: pData
        }).success(function(result){
            if(result.status.code=='0'){
                $scope.items = result.data.resultList;
                $scope.totalNum = result.data.total;
                var pageCount = result.data.pages;//eval("(" + data + ")").pageCount; //取到pageCount的值(把返回数据转成object类型)
                var currentPage = result.data.pageNum;//eval("(" + data + ")").CurrentPage; //得到urrentPage
                var options = {
                    bootstrapMajorVersion: 1, //版本
                    currentPage: currentPage, //当前页数
                    totalPages: pageCount, //总页数
                    numberOfPages:10,//最多显示Page页
                    itemTexts: function (type, page, current) {
                        switch (type) {
                            case "first":
                                return "首页";
                            case "prev":
                                return "上一页";
                            case "next":
                                return "下一页";
                            case "last":
                                return "末页";
                            case "page":
                                return page;
                        }
                    },//点击事件，用于通过Ajax来刷新整个list列表
                    onPageClicked: function (event, originalEvent, type, page) {
                        pData.pageNo=page;
                        $http({
                            url:url,
                            method: 'POST',
                            params: pData
                        }).success(function(result){
                            $scope.totalNum = result.data.total;
                            $scope.items = result.data.resultList;
                            $scope.openIds=false;
                        }).error(function(){
                            console.log("error");
                        })
                        //$.ajax({
                        //    url: "/OA/Setting/GetDate?id=" + page,
                        //    type: "Post",
                        //    data: "page=" + page,
                        //    success: function (data1) {
                        //        if (data1 != null) {
                        //
                        //        }
                        //    }
                        //});
                    }
                };
                $('#pagination').bootstrapPaginator(options);

            }else{
                alert(result.status.msg);
            }
        }).error(function(){
            console.log("error");
        })
    };

    $scope.choseArr=[];//定义数组用于存放前端显示
    var str="";//
    var flag='';//是否点击了全选，是为a
    $scope.openIds=false;//默认未选中
    $scope.checkAll= function (checkboxAll,items) {// 全选
        var c = $scope.checkboxAll;
        if(c==true){
            //alert('1');
            $scope.openIds=true;
            for(var i=0;i<items.length;i++){
                $scope.choseArr[i]=''+items[i].openIid+'';
            }
        }else{
            $scope.openIds=false;
            $scope.choseArr=[""];
            //for(var i=0;i<arr.length;i++){
            //    $scope.arr[i].isSelect=false;
            //}
        }
        flag='a';
        //console.log($scope.choseArr);
    };
    $scope.chk= function (openIid,openIds) {//单选或者多选
        if(flag=='a') {//在全选的基础上操作
            str = $scope.choseArr.join(',') + ',';
        }
        if (openIds == true) {//选中
            str = str + openIid + ',';
        } else {
            str = str.replace(openIid + ',', '');//取消选中
        }

        $scope.choseArr=(str.substr(0,str.length-1)).split(',');
        //console.log($scope.choseArr);
    };


    //获取分类
    $http({
        url:'figure/services/category/getAllLeafCategory.json',
        method: 'get'
    }).success(function(result){
        if(result.status.code=='0'){
            $scope.categorys = result.data;
        }else{
            alert(result.status.msg);
        }
        //console.log("success!");
        //window.location.href = "html/index.html";
    }).error(function(){
        console.log("获取分类出错！");
    })

    //获取标签
    $http({
        url:'figure/services/category/getItemTag.json',
        method: 'get'
    }).success(function(result){
        if(result.status.code=='0'){
            $scope.tags = result.data;
        }else{
            alert(result.status.msg);
        }
        //console.log("success!");
        //window.location.href = "html/index.html";
    }).error(function(){
        console.log("获取分类出错！");
    })

    //设置类目
    $scope.saveCategoryBtn= function () {
        if(!$scope.choseArr || $scope.choseArr.length<=0){
            return;
        }
        $scope.itemDatas=[];//定义数组用于存放前端显示
        for(var i=0;i<$scope.choseArr.length;i++){
            for(var j=0;j<$scope.items.length;j++){
                if($scope.choseArr[i]==$scope.items[j].openIid){
                    $scope.itemDatas[i] = $scope.items[j];
                    break
                }
            }
        }
        if($scope.itemDatas.length<=0){
            return;
        }
        var categoryIdStr = '';
        angular.forEach($scope.categoryModel, function(data,index,array){
            //data等价于array[index]
            //console.log(data.a+'='+array[index].a);
            if(categoryIdStr==''){
                categoryIdStr = data.id;
            }else{
                categoryIdStr = categoryIdStr + ',' + data.id;
            }
        });
        var pData = {itemList:angular.toJson($scope.itemDatas),categoryId:categoryIdStr};
        var url = 'figure/services/admin/item/saveItemCategory.json';
        $http({
            url: url,
            method: 'post',
            data: $.param(pData),
            headers: {'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}
        }).success(function(result){
            if(result.status.code=='0'){
                alert("设置成功！");
            }else{
                alert(result.status.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            console.log("设置类目异常！");
        })
    };

    //设置标签
    $scope.saveTagBtn= function () {
        if(!$scope.choseArr || $scope.choseArr.length<=0){
            return;
        }
        $scope.itemDatas=[];//定义数组用于存放前端显示
        for(var i=0;i<$scope.choseArr.length;i++){
            for(var j=0;j<$scope.items.length;j++){
                if($scope.choseArr[i]==$scope.items[j].openIid){
                    $scope.itemDatas[i] = $scope.items[j];
                    break
                }
            }
        }
        if($scope.itemDatas.length<=0){
            return;
        }
        var tagIdStr = '';
        angular.forEach($scope.tagModel, function(data,index,array){
            //data等价于array[index]
            //console.log(data.a+'='+array[index].a);
            if(tagIdStr==''){
                tagIdStr = data.id;
            }else{
                tagIdStr = tagIdStr + ',' + data.id;
            }
        });
        var pData = {itemList:angular.toJson($scope.itemDatas),categoryId:tagIdStr};
        var url = 'figure/services/admin/item/saveItemCategory.json';
        $http({
            url: url,
            method: 'post',
            data: $.param(pData),
            headers: {'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}
        }).success(function(result){
            if(result.status.code=='0'){
                alert("设置成功！");
            }else{
                alert(result.status.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            console.log("设置标签异常！");
        })
    };

    //设置热销品
    $scope.saveHotBtn= function () {
        if(!$scope.choseArr || $scope.choseArr.length<=0){
            return;
        }
        $scope.itemDatas=[];//定义数组用于存放前端显示
        for(var i=0;i<$scope.choseArr.length;i++){
            for(var j=0;j<$scope.items.length;j++){
                if($scope.choseArr[i]==$scope.items[j].openIid){
                    $scope.itemDatas[i] = $scope.items[j];
                    break
                }
            }
        }
        if($scope.itemDatas.length<=0){
            return;
        }
        var pData = {itemList:angular.toJson($scope.itemDatas)};
        var url = 'figure/services/admin/item/saveHotItems.json';
        $http({
            url: url,
            method: 'post',
            data: $.param(pData),
            headers: {'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}
        }).success(function(result){
            if(result.status.code=='0'){
                alert("设置成功！");
            }else{
                alert(result.status.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            console.log("设置标签异常！");
        })
    };

    //设置版主推荐
    $scope.saveRecomBtn= function () {
        if(!$scope.choseArr || $scope.choseArr.length<=0){
            return;
        }
        $scope.itemDatas=[];//定义数组用于存放前端显示
        for(var i=0;i<$scope.choseArr.length;i++){
            for(var j=0;j<$scope.items.length;j++){
                if($scope.choseArr[i]==$scope.items[j].openIid){
                    $scope.itemDatas[i] = $scope.items[j];
                    break
                }
            }
        }
        if($scope.itemDatas.length<=0){
            return;
        }
        var pData = {itemList:angular.toJson($scope.itemDatas)};
        var url = 'figure/services/admin/item/saveRecommendItems.json';
        $http({
            url: url,
            method: 'post',
            data: $.param(pData),
            headers: {'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}
        }).success(function(result){
            if(result.status.code=='0'){
                alert("设置成功！");
            }else{
                alert(result.status.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            console.log("设置标签异常！");
        })
    };
});

page4.controller('bannerCtrl', function($scope, $rootScope, $http,$location) {

    $http({
        url:'figure/services/item/getBanners.json',
        method: 'POST'
    }).success(function(result){
        if(result.status.code=='0'){
            $scope.items = result.data;
        }else{
            alert(result.status.msg);
        }
    }).error(function(){
        console.log("error");
    })
//        $http.get("/try/angularjs/data/Customers_JSON.php")
//                .success(function (response) {$scope.items = response.records;});
});

page4.controller('addBannerCtrl', function($scope, $rootScope, $http,$location) {
    $scope.typeSelects = [
        {name : "商品", value : "0"},
        {name : "类目", value : "1"},
        {name : "链接", value : "2"}
    ];
    $scope.saveBannerBtn= function () {
        var pData = {name:$scope.name,imgUrl:$scope.imgUrl,type:$scope.type.value,content:$scope.content};
        var url = 'figure/services/admin/item/saveBanner.json';
        $http({
            url: url,
            method: 'post',
            data: $.param(pData),
            headers: {'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}
        }).success(function(result){
            if(result.status.code=='0'){
                alert("新增成功！");
            }else{
                alert(result.status.msg);
            }
            //console.log("success!");
            //window.location.href = "html/index.html";
        }).error(function(){
            console.log("新增异常！");
        })
    };
});
